import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import { ControllerType } from "@/components/items-list/ItemsList";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Form from "antd/lib/form";
import Input from "antd/lib/input";
import Row from "antd/lib/row";
import Table from "antd/lib/table";
import ConfigProvider from "antd/lib/config-provider";
import Modal from "antd/lib/modal";
import Radio from "antd/lib/radio";
import Divider from "antd/lib/divider";
import zhCN from 'antd/es/locale/zh_CN';
import Customer from "@/services/customer";
import notification from "@/services/notification";
import { currentUser } from "@/services/auth";
import { get } from "lodash";
import CreateCustomersDialog from "@/components/enums/CustomersDialog";
import routes from "@/services/routes";

const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
const { confirm } = Modal;
class CustomersList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("customerslistpagesize") ? (localStorage.getItem("customerslistpagesize") !== undefined ? Number(localStorage.getItem("customerslistpagesize")) : 20) : 20,
    blnisinactive: localStorage.getItem("customerslistblnisinactive") ? (localStorage.getItem("customerslistblnisinactive") !== undefined ? Number(localStorage.getItem("customerslistblnisinactive")) : 1) : 1,
    total: 15,
    loading: false,
    code: '',
    name: '',
    data: [],
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
  items = [{
    name: "cght",
    slug: "imgs",
    tags: "tags",
    is_draft: "df",
    is_archived: true
  }];
  componentWillMount() {
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      strcustomercode: this.state.code,
      strcustomername: this.state.name,
      blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
      userid: currentUser.id,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ loading: true });
    Customer.getcustomerlist(params).then(data => {
      this.setState({
        loading: false,
        data: data.data,
        page: params.page,
        pagesize: params.pagesize,
        total: data.total,
      });
    });
  };
  handlesel = () => {
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      strcustomercode: this.state.code,
      strcustomername: this.state.name,
      blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
      userid: currentUser.id,
    }
    this.fetch(param);
  };
  handleDelete = record => {
    if (record.blnisinactive) {
      notification.error("只有在停用状态可以删除，删除失败！");
      return;
    }
    confirm({
      title: '确定删除客户?',
      content: record.strcustomername,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Customer.deletecustomer(record).then(() => {
          notification.success("客户删除成功.");
          let param = {
            page: this.state.page,
            pagesize: this.state.pagesize,
            strcustomercode: this.state.code,
            strcustomername: this.state.name,
            blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
            userid: currentUser.id,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("customerslistpagesize", pagination.pageSize);
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      strcustomercode: this.state.code,
      strcustomername: this.state.name,
      blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
      userid: currentUser.id,
    }
    this.fetch(param);
  };

  handleUpdate = record => {
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      strcustomercode: this.state.code,
      strcustomername: this.state.name,
      blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
      userid: currentUser.id,
    }
    CreateCustomersDialog.showModal({ customers: record })
      .onClose((result = {}) => {
        if (result.success) {
          this.fetch(param);
        }
      }).onDismiss(() => {
      });
  };
  handlestop = record => {

    if(record.blnisinactive){
      record.blnisinactive=false;
    }else{
      record.blnisinactive=true
    }
    Customer.savecustomer(record).then(() => {
      let param = {
        page: this.state.page,
        pagesize: this.state.pagesize,
        strcustomercode: this.state.code,
        strcustomername: this.state.name,
        blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
        userid: currentUser.id,
      }
      this.fetch(param);
    }).catch(error => {
      notification.error("保存失败", error.response.data.message);
    });
  };
  handleadd = () => {
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      strcustomercode: this.state.code,
      strcustomername: this.state.name,
      blnisinactive: this.state.blnisinactive===0 ? "all":(this.state.blnisinactive===1 ? "true":"false"),
      userid: currentUser.id,
    }
    let record = { id: 0, }
    CreateCustomersDialog.showModal({ customers: record })
      .onClose((result = {}) => {
        if (result.success) {
          this.fetch(param);
        }
      }).onDismiss(() => {
      });
  };
  onDragEnter = info => {
    window.console.log(info);
  };
  blnisinactivechange = (e) => {
    localStorage.setItem("customerslistblnisinactive", e.target.value);
    this.setState({
      blnisinactive: e.target.value,
      data: [],
    });
  };
  render() {
    const paginationProps = {
      showSizeChanger: true,
      // showQuickJumper: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "15", "20", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    const listcolumns = [
      // {
      //   title: '单位编码',
      //   key: 'strcustomercode',
      //   dataIndex: 'strcustomercode',
      //   // render: (text, record) => (
      //   //   <a className="clickable" onClick={() => this.handleUpdate(record)}>{text}</a>
      //   // ),
      //   sorter: (a, b) => a.strcustomercode > b.strcustomercode ? 1 : -1
      // },
      {
        title: '单位名称',
        dataIndex: 'strcustomername',
        key: 'strcustomername',
        sorter: (a, b) => a.strcustomername > b.strcustomername ? 1 : -1
      },
      {
        title: '联系人',
        dataIndex: 'representative',
        key: 'representative',
        sorter: (a, b) => a.representative > b.representative ? 1 : -1
      },
      {
        title: '电话',
        dataIndex: 'mobile',
        key: 'mobile',
        sorter: (a, b) => a.mobile > b.mobile ? 1 : -1
      },
      {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
        sorter: (a, b) => a.address > b.address ? 1 : -1
      },
      {
        title: '录入人',
        dataIndex: 'username',
        key: 'username',
        sorter: (a, b) => a.username > b.username ? 1 : -1
      },
      // {
      //   title: '启用',
      //   dataIndex: 'blnisinactive',
      //   key: 'blnisinactive',
      //   render: (text, record) => (
      //     <span>
      //       <Checkbox checked={text}></Checkbox>
      //     </span>
      //   ),
      //   sorter: (a, b) => a.blnisinactive > b.blnisinactive ? 1 : -1
      // },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <a className="clickable" onClick={() => this.handleUpdate(record)}>编辑</a>
            &nbsp;&nbsp;&nbsp;
            <a className="clickable" onClick={() => this.handlestop(record)}>{record.blnisinactive ? "停用":"启用"}</a>
            &nbsp;&nbsp;&nbsp;
            <a className="clickable" onClick={() => this.handleDelete(record)}>删除</a>
          </span>
        ),
      },
    ];
    return (
      <div style={{ margin: 10 }}>
        <ConfigProvider locale={zhCN}>
          <div className="container">
            <PageHeader title="客户列表" />
          </div>
          <Form layout="horizontal" {...{ labelCol: { span: 4 }, wrapperCol: { span: 14 }, }}>
            <Row>
              <Col span={8}>
                <Form.Item style={{ marginBottom: 5 }} label="编码">
                  <Input
                    value={this.state.code}
                    onChange={e => this.setState({ code: e.target.value })}
                    placeholder="编码"
                    autoFocus
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item style={{ marginBottom: 5 }} label="名称">
                  <Input
                    value={this.state.name}
                    onChange={e => this.setState({ name: e.target.value })}
                    placeholder="名称"
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Radio.Group onChange={this.blnisinactivechange}
                  style={{ width: "100%" }}
                  value={this.state.blnisinactive}>
                  <Radio value={0}>所有</Radio>
                  <Radio value={1}>已启用</Radio>
                  <Radio value={2}>已停用</Radio>
                </Radio.Group>
              </Col>
            </Row>
            <Row>
              <Col span={10}>
                <Button type="primary" onClick={() => this.handlesel()} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handleadd()} >
                  <i className="fa fa-plus m-r-5" />
                  新增
                </Button>
              </Col>
            </Row>
          </Form>
          <div>
            <Table rowKey='id'
              rowClassName={(record, index) => getRowClassName(record, index)}
              columns={listcolumns}
              scroll={{ x: 'max-content' }}
              dataSource={this.state.data}
              pagination={paginationProps}
              loading={this.state.loading}
              onChange={this.handleTableChange}
            />
          </div>
        </ConfigProvider>
      </div>
    );
  }
}

routes.register(
  "Customers.List",
  routeWithUserSession({
    path: "/customers",
    title: "客户",
    render: pageProps => <CustomersList {...pageProps} />,
  })
);
